package com.evaluation_system.controller;

import com.evaluation_system.exception.downloadFailException;
import com.evaluation_system.pojo.DTO.CheckerPageQueryDTO;
import com.evaluation_system.pojo.DTO.EvaluatorPageQueryDTO;
import com.evaluation_system.pojo.DTO.FilePageQueryDTO;
import com.evaluation_system.pojo.DTO.UploaderPageQueryDTO;
import com.evaluation_system.pojo.Result.PageResult;
import com.evaluation_system.pojo.Result.Result;
import com.evaluation_system.pojo.entity.Checker;
import com.evaluation_system.pojo.entity.Evaluator;
import com.evaluation_system.pojo.entity.Uploader;
import com.evaluation_system.pojo.entity.saveFileInfo;
import com.evaluation_system.service.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;



@RestController
@Slf4j
@RequestMapping("/admin/account")
@RequiredArgsConstructor
public class AdminController {

    private final UploaderService uploaderService;
    private final CheckerService checkerService;
    private final EvaluatorService evaluatorService;
    @Autowired
    private RunPyService runPyService;
    @Autowired
    private AdminService adminService;

    @Value("${evaluation.py.script-path}")
    private String pyScriptPath;

    // ========== Uploader ==========
    @GetMapping("/uploader/page")
    public Result<PageResult<Uploader>> getUploaderPage(UploaderPageQueryDTO uploaderPageQueryDTO) {
        log.info("分页查询:{}", uploaderPageQueryDTO);
        return Result.success(uploaderService.pageQuery(uploaderPageQueryDTO));
    }

    @PostMapping("/uploader")
    public Result<String> addUploader(@RequestBody Uploader uploader) {
        log.info("添加对象:{}", uploader);
        uploaderService.add(uploader);
        return Result.success("添加成功");
    }

    @PutMapping("/uploader")
    public Result<String> updateUploader(@RequestBody Uploader uploader) {
        log.info("修改对象:{}", uploader);
        uploaderService.update(uploader);
        return Result.success("更新成功");
    }

    @DeleteMapping("/uploader/{id}")
    public Result<String> deleteUploader(@PathVariable Integer id) {
        log.info("删除id为{}的数据", id);
        uploaderService.deleteById(id);
        return Result.success("删除成功");
    }

    // ========== Checker ==========
    @GetMapping("/checker/page")
    public Result<PageResult<Checker>> getCheckerPage(CheckerPageQueryDTO checkerPageQueryDTO) {
        return Result.success(checkerService.pageQuery(checkerPageQueryDTO));
    }

    @PostMapping("/checker")
    public Result<String> addChecker(@RequestBody Checker checker) {
        checkerService.add(checker);
        return Result.success("添加成功");
    }

    @PutMapping("/checker")
    public Result<String> updateChecker(@RequestBody Checker checker) {
        checkerService.update(checker);
        return Result.success("更新成功");
    }

    @DeleteMapping("/checker/{id}")
    public Result<String> deleteChecker(@PathVariable Integer id) {
        checkerService.deleteById(id);
        return Result.success("删除成功");
    }

    // ========== Evaluator ==========
    @GetMapping("/evaluator/page")
    public Result<PageResult<Evaluator>> getEvaluatorPage(EvaluatorPageQueryDTO evaluatorPageQueryDTO) {
        return Result.success(evaluatorService.pageQuery(evaluatorPageQueryDTO));
    }

    @PostMapping("/evaluator")
    public Result<String> addEvaluator(@RequestBody Evaluator evaluator) {
        evaluatorService.add(evaluator);
        return Result.success("添加成功");
    }

    @PutMapping("/evaluator")
    public Result<String> updateEvaluator(@RequestBody Evaluator evaluator) {
        evaluatorService.update(evaluator);
        return Result.success("更新成功");
    }

    @DeleteMapping("/evaluator/{id}")
    public Result<String> deleteEvaluator(@PathVariable Integer id) {
        evaluatorService.deleteById(id);
        return Result.success("删除成功");
    }

    @GetMapping("/file/list")
    public Result<PageResult<saveFileInfo>> getAdminPage(FilePageQueryDTO filePageQueryDTO) {

        log.info("分页查询:{}", filePageQueryDTO);

        return Result.success(adminService.readFile(filePageQueryDTO));
    }

    @GetMapping("/RulesAnalysis")
    public void RulesAnalysis(HttpServletResponse response) throws IOException, downloadFailException {
//        String pyFilePath = "src/main/java/com/evaluation_system/attackPyFile/RulesAnalysis.py";
//        String generateTxtFilePath = "src/main/java/com/evaluation_system/attackPyFile/123.txt";
        String pyFilePath = pyScriptPath + "RulesAnalysis.py";
        String generateTxtFilePath = pyScriptPath + "RulesAnalysis.txt";
        byte[] bytes = runPyService.RulesAnalysis(pyFilePath,generateTxtFilePath);

        log.info("文件内容：{}", bytes);
        // 设置响应头
        String fileName = "RulesAnalysis" + ".txt";// 修改为.txt后缀
        response.setContentType("text/plain");        // 修改为text/plain
        response.setHeader(
                "Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""
        );
        response.setContentLength(bytes.length);   // 变量名改为txtBytes（可选）

// 写入响应流
        try (OutputStream out = response.getOutputStream()) {
            out.write(bytes);  // 写入字节数组
            out.flush();
        }
    }

    @GetMapping("/ApplicationAnalysis")
    public void ApplicationAnalysis(HttpServletResponse response) throws IOException, downloadFailException {
//        String pyFilePath = "src/main/java/com/evaluation_system/attackPyFile/ApplicationAnalysis.py";
//        String generateTxtFilePath = "src/main/java/com/evaluation_system/attackPyFile/ApplicationAnalysis.txt";
        String pyFilePath = pyScriptPath + "ApplicationAnalysis.py";
        String generateTxtFilePath = pyScriptPath + "ApplicationAnalysis.txt";
        byte[] bytes =runPyService.ApplicationAnalysis(pyFilePath,generateTxtFilePath);

        log.info("文件内容：{}", bytes);
        // 设置响应头
        String fileName = "ApplicationAnalysis" + ".txt";// 修改为.txt后缀
        response.setContentType("text/plain");        // 修改为text/plain
        response.setHeader(
                "Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""
        );
        response.setContentLength(bytes.length);   // 变量名改为txtBytes（可选）

// 写入响应流
        try (OutputStream out = response.getOutputStream()) {
            out.write(bytes);  // 写入字节数组
            out.flush();
        }
    }

    @GetMapping("/ReplyAttack")
    public void ReplyAttack(HttpServletResponse response) throws IOException, downloadFailException {
//        String pyFilePath = "src/main/java/com/evaluation_system/attackPyFile/ReplyAttack.py";
//        String generateTxtFilePath = "src/main/java/com/evaluation_system/attackPyFile/ReplyAttackGeNFile.txt";
        String pyFilePath = pyScriptPath + "ReplyAttack.py";
        String generateTxtFilePath = pyScriptPath + "ReplyAttackGeNFile.txt";
        byte[] bytes =runPyService.ReplyAttack(pyFilePath,generateTxtFilePath);

        log.info("文件内容：{}", bytes);
        // 设置响应头
        String fileName = "ReplyAttack" + ".txt";// 修改为.txt后缀
        response.setContentType("text/plain");        // 修改为text/plain
        response.setHeader(
                "Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""
        );
        response.setContentLength(bytes.length);   // 变量名改为txtBytes（可选）

// 写入响应流
        try (OutputStream out = response.getOutputStream()) {
            out.write(bytes);  // 写入字节数组
            out.flush();
        }
    }

    @GetMapping("/XssAttack")
    public void XssAttack(HttpServletResponse response) throws IOException, downloadFailException {
//        String pyFilePath = "src/main/java/com/evaluation_system/attackPyFile/XssAttack1.py";
//        String generateTxtFilePath = "src/main/java/com/evaluation_system/attackPyFile/XssAttackGeNFile.txt";
        String pyFilePath = pyScriptPath + "XssAttack1.py";
        String generateTxtFilePath = pyScriptPath + "XssAttackGeNFile.txt";
        byte[] bytes =runPyService.XssAttack(pyFilePath,generateTxtFilePath);

        log.info("文件内容：{}", bytes);
        // 设置响应头
        String fileName = "XssAttack" + ".txt";// 修改为.txt后缀
        response.setContentType("text/plain");        // 修改为text/plain
        response.setHeader(
                "Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""
        );
        response.setContentLength(bytes.length);   // 变量名改为txtBytes（可选）

// 写入响应流
        try (OutputStream out = response.getOutputStream()) {
            out.write(bytes);  // 写入字节数组
            out.flush();
        }
    }

    @GetMapping("/SqlAttack")
    public void SqlAttack(HttpServletResponse response) throws IOException, downloadFailException {
//        String pyFilePath = "src/main/java/com/evaluation_system/attackPyFile/SqlAttack.py";
//        String generateTxtFilePath = "src/main/java/com/evaluation_system/attackPyFile/SqlAttackGeNFile.txt";
        String pyFilePath = pyScriptPath + "SqlAttack.py";
        String generateTxtFilePath = pyScriptPath + "SqlAttackGeNFile.txt";
        byte[] bytes =runPyService.SqlAttack(pyFilePath,generateTxtFilePath);

        log.info("文件内容：{}", bytes);
        // 设置响应头
        String fileName = "SqlAttack" + ".txt";// 修改为.txt后缀
        response.setContentType("text/plain");        // 修改为text/plain
        response.setHeader(
                "Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""
        );
        response.setContentLength(bytes.length);   // 变量名改为txtBytes（可选）

// 写入响应流
        try (OutputStream out = response.getOutputStream()) {
            out.write(bytes);  // 写入字节数组
            out.flush();
        }
    }


}
